<template>
  <el-form-item :label="'输入模型属性(新)'">
    <template style="display: flex; align-items: center">
      <el-tree-select
        :style="{ flex: '1', minWidth: '160px' }"
        v-model="selectedValue"
        :clearable="false"
        :data="modelSelectTreeOptions"
        :props="treeProps"
        placeholder="请选择输入模型属性"
        @current-change="handleSelectChange"
        @change="handleSelectChange"
      >
        <template #default="{ node, data }">
          {{ node.label }}
        </template>
      </el-tree-select>
    </template>
  </el-form-item>
</template>

<script>
import i18n from '@/utils/i18n'
import { get, isArray, cloneDeep } from 'lodash-es'
import { EVENT_BUS_KEY } from '@/utils/constants'
import eventBus from '@/utils/event-bus.js'
import { convertTreeToPathMap } from '@/utils/util'
import { useJsonSchemaToTree } from '@/components/form-designer/setting-panel/data-source-setting/subscription-service/components/content/composables/useJsonSchemaToTree'
import { getModelPublishVersionByPathOfFetch, getModelSchemaByPathOfFetch } from '@/utils/form'
import { convertModelPropertiesToTreeNodes } from '@/utils/model-converter'

export default {
  name: 'modelSelectFieldKey-editor',
  mixins: [i18n],
  props: {
    designer: Object,
    selectedWidget: Object,
    optionModel: Object,
  },
  data() {
    return {
      modelSelectTreeOptions: [{ name: '表单模型', id: 'root', code: 'root', children: [] }],
      selectedValue: '',
      treeProps: {
        label: 'name',
        value: 'code',
        children: 'children',
        disabled: (node) => !node.isProperty,
      },
    }
  },
  mounted() {
    // console.log(
    //   'this.selectedWidget',
    //   this.selectedWidget,
    //   this.optionModel,
    //   this.designer.formConfig
    // )

    // eventBus.$on(
    //   EVENT_BUS_KEY.FORM_DESIGNER_MODEL_SELECT_TREE_CHANGE,
    //   this.getModelPropertiesFields
    // )
    this.getModelPropertiesFields()
    const modelId = this.selectedWidget.options.modelId
    const modelSelectFieldKey = this.selectedWidget.options.modelSelectFieldKey
    window.$wujie?.bus.$on('getServiceTree', (serviceTree) => {
      const checkedServices = serviceTree
      console.log('checkedServices', checkedServices, this.designer)
      this.handleChange(this.selectedValue, 'local')
    })
    // console.log(modelId, modelSelectFieldKey, 'modelId, modelSelectFieldKey')
    if (modelId && modelSelectFieldKey?.length) {
      this.handleChange(`${modelId}__${modelSelectFieldKey[0]}`)
      this.selectedValue = `${modelId}__${modelSelectFieldKey[0]}`
    }
  },
  watch: {
    // 监听选中组件处理初始值
    selectedWidget: {
      handler(newVal, oldVal) {
        // console.log('newVal', newVal, 'oldVal', oldVal)
        const modelId = newVal.options.modelId
        const modelSelectFieldKey = newVal.options.modelSelectFieldKey
        if (modelId && modelSelectFieldKey?.length) {
          this.handleChange(`${modelId}__${modelSelectFieldKey[0]}`, 'watch view')
          this.selectedValue = `${modelId}__${modelSelectFieldKey[0]}`
        } else {
          // 新增加组件 默认空值
          this.handleChange('', 'watch add')
          this.selectedValue = ''
        }
      },
    },
  },
  methods: {
    // 组装模型选择树
    async getModelPropertiesFields() {
      // 1. 获取所有模型的发布版本 Id
      const allPublishVersionIds = await getModelPublishVersionByPathOfFetch(
        `/formConfig/datamodel/PubilshModelVersion.js`
      )
      // 2. 获取所有模型存在的 内容 schema
      const modelSchemaMap = await getModelSchemaByPathOfFetch(allPublishVersionIds || [])
      const modelSelectTree = this.designer.formConfig.modelSelectTree?.[0]?.children ?? []

      // 如果返回的是 modelIdMapProperties 格式，则使用它，否则直接使用返回的数据
      const schemaData = modelSchemaMap.modelIdMapProperties || modelSchemaMap
      const result = convertModelPropertiesToTreeNodes(schemaData, modelSelectTree)
      this.modelSelectTreeOptions[0].children = result
      // 存储表单模型树
      this.designer.formConfig.modelFormTree = this.modelSelectTreeOptions
      console.log('表单模型树数据已更新:', this.modelSelectTreeOptions)
    },

    // 获取模型树所有 节点 Id
    getAllIds(data) {
      const ids = []
      const collectIds = (items) => {
        if (!Array.isArray(items)) return
        items.forEach((item) => {
          if (item.id) {
            ids.push(item.id)
          }
          if (Array.isArray(item.children)) {
            collectIds(item.children)
          }
        })
      }
      collectIds(data)
      return ids
    },

    // 通过GET请求获取模型数据
    async fetchModelData(url) {
      try {
        const response = await fetch(url)
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        // 由于返回的是JS文件，我们需要以文本形式获取
        const text = await response.text()
        console.log('通过GET请求获取的JS内容:', text)
        console.log(text, 'text', typeof text)
      } catch (error) {
        console.error('获取模型数据失败:', error)
      }
    },

    // 下拉树 选择表单模型
    handleSelectChange(val, local = '') {
      this.selectedValue = val
      // 自动触发关联服务功能
      this.handleServiceClick()
    },
    // 选择模型字段
    handleChange(val) {
      // console.log(val, 'val', this.designer.formConfig, this.modelSelectTreeOptions)
      if (!val) {
        // 去掉清空按钮，不存在删除或者清空的情况，保证关联模型始终有值，理论上这个条件不存在
        // 为了清空选择的模型字段，需要将模型树清空 component = []
        this.designer.formConfig?.serviceVersionVOs.forEach((item) => {
          item.inputModelTree.forEach((item2) => {
            item2.children.forEach((item3) => {
              item3.component = []
            })
          })
        })
        // 清空选择的模型字段
        this.selectedWidget.options.modelSelectFieldKey = []
        this.selectedWidget.options.modelId = ''
      } else {
        const serviceVO = this.designer.formConfig?.serviceVersionVOs || []
        const [modelId, fieldKey] = val?.split('__') || []
        this.selectedValue = val
        serviceVO.forEach((item) => {
          useJsonSchemaToTree(item, 'inputModel')
          if (item.inputModel) {
            if (item.inputModel.dataModelId === modelId) {
              console.log('item.inputModel', item, item.inputModel, val, 'val222')
              this.updateFSSVVO('inputModel', item, fieldKey, this.optionModel.name, modelId)
            }
          } else {
            console.error(`模型【${item.service.name}】没有输入模型字段：`, item.inputModel)
          }
        })
      }
    },
    // 关联服务 2025年8月11日15:22:43
    handleServiceClick() {
      // this.selectedValue 格式：1955093221177860098__sex
      window.$wujie?.bus.$emit('handleServiceSelect', true, this.selectedValue?.split('__')[0])
    },
    /**
     * 更新表单服务版本视图对象
     * 该函数通过比较当前表单服务版本和最新服务版本的模型树，来更新当前服务版本视图对象
     * @param {string} modelType - 模型类型，可以是 'inputModel' 或 'outputModel'
     */
    updateFSSVVO(modelType, item, fieldKey, componentName, modelId) {
      // 创建当前表单服务版本的模型路径映射
      const cFormMap = new Map()
      // 将当前表单服务版本的模型树转换为路径映射
      convertTreeToPathMap(
        modelType === 'inputModel' ? item.inputModelTree : item.outputModelTree,
        '',
        cFormMap
      )
      // 深拷贝最新服务版本视图对象，以避免直接修改原始对象
      // const cloneCLSVVO = cloneDeep(item)
      const cloneCLSVVO = item // TODO 直接修改原对象
      // 遍历最新服务版本的模型路径映射
      // cFormMap.forEach((value, key) => {
      //   // 检查当前表单服务版本是否包含对应路径和类型
      //   if (cFormMap.has(key) && cFormMap.get(key).type === value.type) {
      //     // 根据模型类型更新最新服务版本视图对象的组件
      //     const currentLNode = get(cloneCLSVVO.inputModelTree, value.path)
      //     currentLNode.component = cFormMap.get(key).component
      //   }
      // })
      // const inputModelTreeFind = cloneCLSVVO.inputModelTree?.[0]?.children?.find(item => item.key === fieldKey)
      // const inputModelTreeNotFind = cloneCLSVVO.inputModelTree?.[0]?.children?.find(item => item.key !== fieldKey)
      // console.log(inputModelTreeFind, 'inputModelTreeFind 333', inputModelTreeFind.key, inputModelTreeFind.component);
      // console.log(inputModelTreeNotFind, 'inputModelTreeNotFind 333', inputModelTreeNotFind.key, inputModelTreeNotFind.component);
      // inputModelTreeFind.component = [componentName]
      // inputModelTreeNotFind.component = []
      if (this.selectedWidget.options.name === componentName) {
        this.selectedWidget.options.modelSelectFieldKey = [fieldKey]
        this.selectedWidget.options.modelId = modelId
      }
      cloneCLSVVO.inputModelTree[0].children = cloneCLSVVO.inputModelTree?.[0]?.children?.map(
        (item) => {
          if (item.key === fieldKey) {
            item.component = [componentName]
          } else {
            item.component = []
          }
          return item
        }
      )

      // console.log('updateCFSVVO', cloneCLSVVO)
      this.designer.formConfig.serviceVersionVOs.forEach((item) => {
        if (item.id === cloneCLSVVO.id) {
          item = { ...(cloneCLSVVO || {}) }
        }
      })
      return cloneCLSVVO
    },
  },
}
</script>

<style scoped>
.tree-node-content {
  display: flex;
  align-items: center;
  padding: 5px 0;
  max-width: 450px; /* 限制节点内容最大宽度 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
  white-space: nowrap; /* 不换行 */
}

.el-tree-select {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s;
}

.el-tree-select:hover {
  border-color: #c0c4cc;
}

.el-tree-select:focus-within {
  border-color: #409eff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 美化下拉树菜单 */
.el-tree-select-dropdown .el-tree-node {
  padding: 3px 0;
}

.el-tree-select-dropdown .el-tree-node.is-current > .el-tree-node__content {
  background-color: #f5f7fa;
  color: #409eff;
}

.el-tree-select-dropdown .el-tree-node.is-selected > .el-tree-node__content {
  background-color: #f0f7ff;
  color: #409eff;
}
</style>
